﻿#include "tabgroupchat.h"
#pragma execution_character_set("utf-8")
TabGroupChat::TabGroupChat()
{
    init();
    this->setStyleSheet("QWidget {"
                        "   background-color: #F5F5F5;"
                        "   border-radius: 15px;"
                        "}");
}

void TabGroupChat::init() {
    groupScrollArea = new QScrollArea(this);
    groupScrollArea->setFixedSize(300,550);
    scrollContainer = new QWidget(this);
    scrollLayout = new QVBoxLayout();
    scrollContainer->setLayout(scrollLayout);
    groupScrollArea->setWidget(scrollContainer);

    scrollContainer->setFixedSize(290, 500);

    chatroom = new Chatroom(Operation::SendGroupTextMsg);
    chatroom->init();

    QHBoxLayout *hBoxLayout = new QHBoxLayout();
    hBoxLayout->addWidget(groupScrollArea);
    hBoxLayout->addWidget(chatroom);

    setLayout(hBoxLayout);


}

void TabGroupChat::setGroupRecentContactList(QList<RecentContact> recentContactList) {
    this->groupRecentContactList = recentContactList;
}

void TabGroupChat::initGroupRecentContactList(QJsonDocument doc) {
    for (auto each: doc.object()["recentGroup"].toArray()) {
        RecentContact tmpRecentContact;
        tmpRecentContact.id = each.toObject()["id"].toInt();
        tmpRecentContact.time = each.toObject()["recentTime"].toString();
        tmpRecentContact.nickname = each.toObject()["name"].toString();
//        tmpRecentContact.avatorPath = each.toObject()["avator"].toString();

        tmpRecentContact.avatorPath = "D:\Qtuber\2\soloavator\4.jpg";

        tmpRecentContact.shortMsg = each.toObject()["recentMsg"].toString();
        qDebug() << tmpRecentContact.toString();
        groupRecentContactList.append(tmpRecentContact);
    }
    generateGroupRecentContactBoxes();
}

void TabGroupChat::generateGroupRecentContactBoxes() {
    for(int i = 0; i < groupRecentContactList.size(); ++i){
        RecentContactBox * box = new RecentContactBox(
                    groupRecentContactList[i].id,
                    groupRecentContactList[i].nickname,
                    groupRecentContactList[i].time,
                    groupRecentContactList[i].shortMsg,
                    groupRecentContactList[i].avatorPath,
                    1);
        myGroupRecentContactBoxes[groupRecentContactList[i].id] = box;

        KeySender *keySender = new KeySender();
        keySender->setId(groupRecentContactList[i].id);

        connect(box, SIGNAL(clicked()), keySender, SLOT(emitId()));
        connect(keySender, SIGNAL(sendId(qint32)), this, SLOT(handleGroupBoxClicked(qint32)));
        scrollLayout->addWidget(box);
    }
    this->scrollLayout->addStretch();
}

void TabGroupChat::handleGroupBoxClicked(qint32 id) {
    qDebug() << "handleBoxClicked(qint32 " << id << ")";
    chatroom->setReId(id);
    chatroom->clearMsg();
    QString path = CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/grouphistory/%1.json").arg(id);
    QFile file(path);
    if ( !file.exists() ) {
        qDebug() << "文件打开失败!\n";
        QJsonArray historyArray;
        QJsonDocument doc;
        QJsonObject obj;
        obj.insert("history", historyArray);
        doc.setObject(obj);
        QFile jsonfile(path);
        jsonfile.open(QIODevice::WriteOnly);
        jsonfile.write(doc.toJson());
        jsonfile.close();
    }
    else{
        qDebug() << "文件打开成功";

        file.open(QIODevice::ReadOnly);
        QJsonParseError error;
        QJsonDocument doc = QJsonDocument::fromJson(file.readAll(),&error);

        if(!doc.isNull() && error.error == QJsonParseError::NoError) {
            QJsonObject jsonObject = doc.object();
            if ( jsonObject.contains( "history" ) && jsonObject.value( "history" ).isArray() ) {
                QJsonArray jsonArray = jsonObject.value( "history" ).toArray();
                for ( int i = 0; i < jsonArray.size(); i++ ) {
                    if ( jsonArray[ i ].isObject() ) {
                        QJsonObject jsonObjectPost = jsonArray[ i ].toObject();
                        if ( jsonObjectPost.contains( "senderId" ) &&
                             jsonObjectPost.contains( "type" ) &&
                             jsonObjectPost.contains( "time" ) &&
                             jsonObjectPost.contains( "data" )) {
                            //发送者为自己时
                            if( jsonObjectPost["senderId"].toInt() == CONF.userId){
                                MyChatItem * mychatItem = new MyChatItem();
                                QString avatorPath = CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/soloavator/%1.jpg").arg(jsonObjectPost["senderId"].toInt());
                                qDebug() << "group member avator path:" << avatorPath;
                                mychatItem->setAvator(avatorPath);
                                mychatItem->setTime(jsonObjectPost.value( "time" ).toString());
                                if(jsonObjectPost.value( "type" ).toString() == "text"){
                                    mychatItem->setMsg(jsonObjectPost.value( "data" ).toString());

                                    myGroupRecentContactBoxes[id]->changeTime(jsonObjectPost.value( "time" ).toString());
                                    myGroupRecentContactBoxes[id]->changeMsg(jsonObjectPost.value( "data" ).toString());
                                }
                                else if(jsonObjectPost.value( "type" ).toString() == "img"){
                                    qDebug() <<"picture path ::" << CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString();
                                    mychatItem->addPic(CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString());

                                    myGroupRecentContactBoxes[id]->changeTime(jsonObjectPost.value( "time" ).toString());
                                    myGroupRecentContactBoxes[id]->changeMsg("A picture");
                                }
                                //                            TODO: 文件展示
                                else if(jsonObjectPost.value( "type" ).toString() == "file"){
                                    myGroupRecentContactBoxes[id]->changeTime(jsonObjectPost.value( "time" ).toString());
                                    myGroupRecentContactBoxes[id]->changeMsg("A file");
                                }
                                chatroom->addNewWidget(mychatItem);
                            }
                            else{
                                ChatItem * chatItem = new ChatItem();
                                QString avatorPath = CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/soloavator/%1.jpg").arg(jsonObjectPost["senderId"].toInt());
                                qDebug() << "group member avator path:" << avatorPath;
                                chatItem->setAvator(avatorPath);
                                qDebug() << "group member avator path:" << avatorPath;
                                chatItem->setTime(jsonObjectPost.value( "time" ).toString());
                                if(jsonObjectPost.value( "type" ).toString() == "text"){
                                    chatItem->setMsg(jsonObjectPost.value( "data" ).toString());
                                }
                                else if(jsonObjectPost.value( "type" ).toString() == "img"){
                                    qDebug() <<"picture path ::" << CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString();
                                    chatItem->addPic(CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString());
                                }
                                //                            TODO: 文件展示
                                else if(jsonObjectPost.value( "type" ).toString() == "file"){
                                }
                                chatroom->addNewWidget(chatItem);
                            }
                        }
                    }
                }
            }
        }
    }
}


